// pages/goods/submit/cluster/cluster.js
// import { agentOrderList , orderPayment , paymentByWarehourse} from '../../../../api/order'

import { list } from '../../../../api/groupOrder';
import{shareinfo}from'../../../../api/groupOrder';
import {
    getInfo,
} from '../../../../api/member'
import {
    getInfo as mchGetInfo
} from '../../../../api/enterprise'
const util = require('../../../../utils/util.js')
let app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        noToken:true,
        haveAvatarUrl: false,
        title: "天天享免单",
        back: "http://cdn.rzico.com/groupImg/goback.png",
        images: "http://cdn.rzico.com/groupImg/back.png",
        thumbnail: "", //头像
        orderId: "2022*******1926", //订单号
        paymentPrice: 109, //订单金额
        groupNum: 2, //组团人数
        total: 50, //返现金额
        award: 199, //
        point: 1999, //返现总金额
        icon: "http://cdn.rzico.com/groupImg/arrow.png",
        img: [
            "http://cdn.rzico.com/groupImg/share.png",
            "http://cdn.rzico.com/groupImg/order.png",
            "http://cdn.rzico.com/groupImg/cash.png",
        ],
        windowWidth: 0,
        windowHeight: 0,
        transparent: 1, //透明度
        currentTab: 0,
        pageNum: 1,
        pageSize: 5,
        groupBuyId:"",
        groupOrderInfo:[],
        type:"",
        orderList:[],
        groupOrderList: [],
        groupStatus:0, //拼团状态
        paymentStatus: 0, // 付款状态
        shippingStatus: 0, // 配送状态
        orderStatus: 0, // 订单状态
        loading: true,
        arr: [],
        triggered: false,
        refreshType: false,
        // dialogImg: "http://cdn.rzico.com/groupImg/popup.png",
        mch:null,
        avatar: "http://cdnx.rzico.com/images/canvasMyLogo.png",//头像链接
        name: "daggen1", //用户呢称
        //  avatar: "",//头像链接
        //  name: "", //用户呢称
        isShow: false,
        shotitle: false,
        single: false,
        level: "一等奖",
        allowance: "本单返现50元"
    },

    /**
     * 生命周期函数--监听页面加载
     */

    onLoad(options) {
        var that = this;
        /**
         * 获取当前设备的宽高
         */
        this.setNavSize();
        this.getInfo();
        this.getInfoClick();

        this.setPaintOrgIdData(options)
        this.getProductData(options)
        // this.loadOrder()
        this.setData({
            groupStatus:'', //拼团状态
            paymentStatus: '', // 付款状态
            shippingStatus: '', // 配送状态
            orderStatus: '', // 订单状态
            currentTab: query.index,
        })
        this.data.refreshType = true
        if (query.index == 0) {
            this.bindChange()
        }
        // console.log("query.index",query.index)
        if (this.isShow) {
            this.modalCandel();
        }
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        var that = this;
        if (app.globalData.token != "" && app.globalData.token != null) {
            this.setData({
                noToken: false
            })
        }
        /*  const {
           userInfo
         } = app.globalData
         if (userInfo) {
           //怎么判断是否已经头像授权
           if (userInfo.hasOwnProperty("avatar")) {
             that.setData({
               haveAvatarUrl: true,
               avatar: app.globalData.userInfo.avatar,
               name: app.globalData.userInfo.nickname,
             })
             console.log("loaded")
           }
          that.avatar=this.data.avatar;
          that.name=this.data.name;
           console.log(this.avatar,this.name,"name")
         }*/
        if (this.data.refreshType == false) {
            this.bindChange()
            console.log('监听页面显示')
            console.log("onLoad ", this.data.orderList)
        }
        this.data.refreshType = false
        this.shareToFriends();
        this.loadShareInfo();
        wx.onAppShow((options) => {
            if ((options.scene === 1037 || options.scene === 1038) && !util.isNull(options.referrerInfo.extraData)) {
                wx.showLoading({
                    title: '查询支付状态',
                })
                const { extraData } = options.referrerInfo
                if (extraData.status == 'success') {
                    wx.hideLoading()
                    this.loadList();
                } else {
                    wx.hideLoading()
                    wx.showToast({
                        title: '支付失败',
                        icon: 'none'
                    })
                }
            }
        })
        // this.setPaintOrgIdData(options);
        // this.getProductData(options);

    },
    // 获取拼团信息的请求
    loadShareInfo() {
        var _this=this;
        //     console.log("口令--" + app.globalData.token)
        let shareInfo = [];
        shareinfo().then(
            res => {
                // console.log("收货地址列表的数据--" + JSON.stringify(res))
                if (res.type == "success") {
                    console.log("shareinfo.res",res)
                    if (res.data.data.length > 0) {
                        console.log("shareinfo.data.data",res.data.data)
                        res.data.data.map((item) => {
                            let shareInfoItem = {}
                            shareInfoItem.groupBuyId= item.groupBuyId
                            /*   groupOrderInfoItem.address = item.address
                            //   groupOrderInfoItem.areaName = item.areaName
                            //   groupOrderInfoItem.building = item.building
                            //   groupOrderInfoItem.roomNumber = item.roomNumber
                            //   groupOrderInfoItem.isDefault = item.isDefault
                            //   groupOrderInfoItem.phone = item.phone
                            //   groupOrderInfoItem.level=item.level
                             */
                            shareInfo.push(shareInfoItem)
                        })
                    }
                    this.setData({
                        shareInfo: shareInfo
                    })
                }
            }
        ).catch(error => {
            console.log(error,"zz")
        })
    },




    //  tab切换逻辑
    swichNav: function (e) {
        var _this = this;
        if (e !== undefined) {
            if (this.data.currentTab === e.target.dataset.current) {
                return false;
            } else {
                _this.data.currentTab = e.target.dataset.current
                _this.setData({
                    currentTab: e.target.dataset.current
                })
            }
        }
    },
    bindChange: function (e) {
        var _this = this;
        console.log("e", e);
        if (!util.isNull(e)) {
            _this.data.currentTab = e.detail.current
        }
        this.data.pageNum = 1;
        this.data.orderList = [];
        this.data.groupOrderList=[];
        var groupStatus = '';       // 拼团状态
        var paymentStatus = '';     // 付款状态
        var shippingStatus = '';    // 配送状态
        var orderStatus = ''        // 订单状态
        switch (_this.data.currentTab) {
            case 0:
                groupStatus = '';   // 拼团状态
                paymentStatus = ''; // 付款状态
                shippingStatus = '';// 配送状态
                orderStatus = ''    // 订单状态
                break;
            case 1:
                groupStatus = 0;    // 拼团状态
                paymentStatus = 0;  // 付款状态
                shippingStatus = 0; // 配送状态
                orderStatus = 0;    // 订单状态
                break;
            case 2:
                groupStatus = 1; // 拼团状态
                paymentStatus = 1; // 付款状态
                shippingStatus = 0; // 配送状态
                orderStatus = 1 // 订单状态
                break;
        }
        _this.setData({
            paymentStatus: paymentStatus,
            shippingStatus: shippingStatus,
            orderStatus: orderStatus,
            currentTab: _this.data.currentTab
        })
        this.loadList();
    },

    loadList() {
        var _this = this
        this.data.loading = false
        wx.showLoading({
            title: '加载中',
        })
        //pages/goods/product/groupDetails
        list({
            pageNum: _this.data.pageNum,
            pageSize: _this.data.pageSize,
            groupStatus:_this.data.groupStatus,//拼团状态
            paymentStatus: _this.data.paymentStatus, // 付款状态
            shippingStatus: _this.data.shippingStatus, // 配送状态
            orderStatus: _this.data.orderStatus, // 订单状态
            mchId: app.globalData.mchId
        }).then(
            res => {
                console.log("loadList.res", res)
                if (res.type == 'success') {
                    res.data.data.forEach(function (item) {
                        item.itemList.forEach(function (il) {
                            il.thumbnail = util.thumbnail(il.thumbnail, 170, 170)
                        })
                        _this.data.orderList.push(item)
                    })
                    console.log("groupOrderList11", _this.data.groupOrderList)
                    console.log("orderList", _this.data.orderList)
                    _this.data.loading = _this.data.pageSize <= res.data.data.length;
                    wx.hideLoading()
                    _this.setData({
                        orderList: _this.data.orderList,
                        // groupOrderList:_this.data.groupOrderList,
                        thumbnail: _this.data.orderList[0].itemList[0].thumbnail, //头像
                        orderId: _this.data.orderList[0].sn, //订单号
                        paymentPrice: _this.data.orderList[0].price, //订单金额
                        groupNum: _this.data.orderList[0].groupNum, //组图人数
                        total: _this.data.orderList[0].total, //返现金额
                        award: _this.data.orderList[0].award,
                        point: _this.data.orderList[0].point //返现总金额
                    })
                    console.log("groupOrderList.sn", _this.data.orderList[0].sn)
                } else {
                    wx.hideLoading()
                }
            }
        ).catch(error => {
            console.log(error)
            this.data.loading = true
            wx.hideLoading()
        })
    },

    reachBottom() {
        var _this = this
        if (_this.data.loading == true) {
            this.data.pageNum = this.data.pageNum + 1;
            this.loadList()
        }
    },

    shareToFriends: function (e) {
        var that = this;
        that.setData({
            isShow: true
        })
    },
    /**
     * 点击取消
     */
    modalCandel: function () {
        var that = this;
        that.setData({
            isShow: false
        })
    },

    /**
     *  点击确认
     */
    modalConfirm: function () {
        var that = this;
        wx.hideLoading()
        /* wx.showModal({/*  // 保存成功后记得提醒用户二维码已经存到他的手机相册了哦
             title: '感谢您获得了大额返现金',
             content: '立即去拼团',
             success: function (res) {
                 if (res.confirm) {
                     //console.log('点击确定')
                 } else if (res.cancel) {
                     //console.log('点击取消')
                 }
             }
         }) */

        that.setData({
            isShow: false
        })
    },

    setNavSize: function () {
        var that = this,
            sysinfo = wx.getSystemInfoSync(),
            statusHeight = sysinfo.statusBarHeight,
            windowWidth = sysinfo.windowWidth,
            windowHeight = sysinfo.windowHeight,
            isiOS = sysinfo.system.indexOf('iOS') > -1,
            navHeight;
        console.log("sysinfo", sysinfo)
        if (!isiOS) {
            navHeight = 48;
        } else {
            navHeight = 44;
        }
        that.setData({
            status: statusHeight,
            navHeight: navHeight,
            windowWidth: windowWidth,
            windowHeight: windowHeight,
        })
    },
    navTo() {
        let p = getCurrentPages().length;
        if (p <= 1) {
            wx.switchTab({
                url: '/pages/index/index',
            })
        } else {
            wx.navigateBack({
                delta: 1
            })
        }
    },
    refresh() {
        // this.triggerEvent('refresh')
        this.bindChange()
    },

    //获取用户信息
    /* getInfo() {
      var _this = this
      getInfo().then(
        res => {
          console.log("getinfo.res",res)
          if (res.type == 'success') {
             this.setData({
              haveAvatarUrl: true,
              // avatar: app.globalData.userInfo.avatar,
              // name: app.globalData.userInfo.nickname,
              avatar: res.userInfo.avatar,
              name: res.userInfo.nickname,
            })
            console.log("avatar",this.avatar,"name",this.name)
          }
        }
      ).catch(error => {
        console.log(error)
      })
    }, */
    getInfo() {
        var that = this
        that.wx.getUserProfile({
            desc: '获取信息原因', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (res) => {
                console.log("获取用户信息成功", res)
                that.setData({//添加及更新UI
                    avatar: res.userInfo.avatarUrl,
                    name:res.userInfo.nickName,
                })
            },
            fail: res => {
                console.log("获取用户信息失败", res)
            }
        })
        console.log("avatar",this.avatar,"name",this.name)
    },



    getInfoClick() {
        let _this = this
        mchGetInfo({ "mchId": app.globalData.mchId }).then(
            res => {
                console.log("getInfoClick",res)
                if (res.type == 'success') {
                    _this.data.mch = res.data
                    _this.setData({
                        mch: _this.data.mch
                    })
                }
            }
        ).catch(error => {
            console.log(error)
        })
    },
    //检测用户的登录状态
    checkLogin(callback) {
        console.info("全局变量app.globalData--" + JSON.stringify(app.globalData))
        if (app.globalData.token == null) {
            wx.navigateTo({
                url: '/pages/login/index',
            })
        } else {
            if (callback) {
                callback()
            }
        }
    },




    /**生命周期函数--监听页面初次渲染完成
     *
     */
    onReady() {

    },


    /**
     * 生命周期函数--监听页面隐藏
     */
    /*     onHide() {

        },
     */
    /**
     * 生命周期函数--监听页面卸载
     */

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        wx.showNavigationBarLoading()
        this.data.pageNum = 1
        setTimeout(() => {
            wx.hideNavigationBarLoading()
            this.loadOrder()
            wx.stopPullDownRefresh()
        }, 1000);
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        this.data.pageNum += 1
        this.loadOrder()
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        console.log(this.data.product.thumbnail + '?x-oss-process=image/resize,m_fixed,h_400,w_500')
        // return this.getShareData();
        return {
            title: this.data.product.name,
            desc: '拼团购,更优惠,还能领返现',
            // imageUrl:thiswx.showShareImageMenu({
            //   path: 'path',
            // })
            imageUrl: this.data.product.thumbnail + '?x-oss-process=image/resize,m_fixed,h_400,w_500',
            path: 'pages/index/index'
        }
    }
})
